package com.example.moshudriver.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.BeeFramework.BeeFrameworkApp;
import com.BeeFramework.model.BeeQuery;
import com.BeeFramework.view.MyDialog;
import com.BeeFramework.view.MyProgressDialog;
import com.baidu.mobstat.SendStrategyEnum;
import com.baidu.mobstat.StatService;
import com.sgr.dykdriver.R;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.example.moshudriver.tools.SESSION;
import com.example.moshudriver.tools.StreamTools;
import com.example.moshudriver.utils.ImageUtils;
import com.testin.agent.TestinAgent;

public class SplashActivity extends Activity {
	protected static final int URL_ERROR = 1;
	protected static final int NETWORK_ERROR = 2;
	protected static final int JSON_ERROR = 3;
	protected static final int SHOW_UPDATE_DIALOG = 4;
	protected static final int LOADIMAGE = 5;
	// protected static final int SHOW_UPDATE_PROGRESS = 5;
	// protected static final int CANCLE_UPDATE_PROGRESS = 6;
	private SharedPreferences mShared;
	private SharedPreferences.Editor mEditor;
	private String description;
	private String apkurl;
	private NotificationManager mNotificationManager;
	private int progress;
	private Drawable drawable;
	private RelativeLayout rl_began;
	private MyProgressDialog myProgressDialog;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final View startView = View.inflate(this, R.layout.splash, null);
		rl_began = (RelativeLayout) startView.findViewById(R.id.rl_began);
		// loadImage();
		setContentView(startView);
/*		TestinAgent.init(this, "97e5ce28444d3147f43faaaeebcac70f",
				"moshudriver");
		// 设置AppKey
		// StatService.setAppKey("a9e2ad84a2"); //
		// appkey必须在mtj网站上注册生成，该设置建议在AndroidManifest.xml中填写，代码设置容易丢失

		
		 * 设置渠道的推荐方法。该方法同setAppChannel（String），
		 * 如果第三个参数设置为true（防止渠道代码设置会丢失的情况），将会保存该渠道，每次设置都会更新保存的渠道，
		 * 如果之前的版本使用了该函数设置渠道
		 * ，而后来的版本需要AndroidManifest.xml设置渠道，那么需要将第二个参数设置为空字符串,并且第三个参数设置为false即可。
		 * appChannel是应用的发布渠道，不需要在mtj网站上注册，直接填写就可以 该参数也可以设置在AndroidManifest.xml中
		 
		// StatService.setAppChannel(this, "RepleceWithYourChannel", true);
		// 测试时，可以使用1秒钟session过期，这样不断的间隔1S启动退出会产生大量日志。
		StatService.setSessionTimeOut(30);
		// setOn也可以在AndroidManifest.xml文件中填写，BaiduMobAd_EXCEPTION_LOG，打开崩溃错误收集，默认是关闭的
		StatService.setOn(this, StatService.EXCEPTION_LOG);
		
		 * 设置启动时日志发送延时的秒数<br/> 单位为秒，大小为0s到30s之间<br/>
		 * 注：请在StatService.setSendLogStrategy之前调用，否则设置不起作用
		 * 
		 * 如果设置的是发送策略是启动时发送，那么这个参数就会在发送前检查您设置的这个参数，表示延迟多少S发送。<br/>
		 * 这个参数的设置暂时只支持代码加入， 在您的首个启动的Activity中的onCreate函数中使用就可以。<br/>
		 
		StatService.setLogSenderDelayed(0);
		
		 * 用于设置日志发送策略<br /> 嵌入位置：Activity的onCreate()函数中 <br />
		 * 
		 * 调用方式：StatService.setSendLogStrategy(this,SendStrategyEnum.
		 * SET_TIME_INTERVAL, 1, false); 第二个参数可选： SendStrategyEnum.APP_START
		 * SendStrategyEnum.ONCE_A_DAY SendStrategyEnum.SET_TIME_INTERVAL 第三个参数：
		 * 这个参数在第二个参数选择SendStrategyEnum.SET_TIME_INTERVAL时生效、
		 * 取值。为1-24之间的整数,即1<=rtime_interval<=24，以小时为单位 第四个参数：
		 * 表示是否仅支持wifi下日志发送，若为true，表示仅在wifi环境下发送日志；若为false，表示可以在任何联网环境下发送日志
		 
		StatService.setSendLogStrategy(this,
				SendStrategyEnum.SET_TIME_INTERVAL, 1, false);
		// 调试百度统计SDK的Log开关，可以在Eclipse中看到sdk打印的日志，发布时去除调用，或者设置为false
		StatService.setDebugOn(true);*/
		if (BeeQuery.environment() == BeeQuery.ENVIROMENT_DEVELOPMENT
				|| BeeQuery.environment() == BeeQuery.ENVIROMENT_MOCKSERVER) {
			BeeFrameworkApp.getInstance().showBug(this);
		}
		boolean update = true;
		mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0);
		mEditor = mShared.edit();
/*
		String imageurl = mShared.getString("imagebitmap", "");
		String loadurl = mShared.getString("loadurl", "");
		loadimageurl = mShared.getString("loadimageurl", "");
		testurl = loadimageurl;
		if ("".equals(imageurl) || !testurl.equals(loadurl)) {
			System.out.println("加载新图片");
			loadImage();
			rl_began.setBackgroundResource(R.drawable.began);
		} else {
			System.out.println("加载缓存图片-------");
			Drawable drawable = new BitmapDrawable(
					ImageUtils.convertStringToIcon(imageurl));
			rl_began.setBackground(drawable);
		}*/
		if (update) {
			checkUpdate();

		} else {
			// 渐变
			AlphaAnimation aa = new AlphaAnimation(1f, 1.0f);
			aa.setDuration(2500);
			startView.setAnimation(aa);
			aa.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					// TODO Auto-generated method stub
					redirectto();
				}
			});
		}

	}

	private void loadImage() {
		// TODO Auto-generated method stub

		new Thread() {

			@SuppressWarnings("deprecation")
			public void run() {
				Message message = Message.obtain();
				try {
					URL url = new URL(testurl);
					// 联网
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					// 请求方式
					conn.setRequestMethod("GET");
					// 请求超时时间
					conn.setConnectTimeout(3000);
					// 获取请求返回码
					int code = conn.getResponseCode();
					if (code == 200) {// 联网成功

						InputStream inputStream = conn.getInputStream();
						System.out.println("流" + inputStream);
						// 把流转化为Bitmap
						Bitmap map = BitmapFactory.decodeStream(inputStream);
						if (map != null) {
							drawable = new BitmapDrawable(map);
							mEditor.putString("imagebitmap",
									ImageUtils.convertIconToString(map));
							mEditor.putString("loadurl", url.toString());
							mEditor.commit();
							message.what = LOADIMAGE;
						}

					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					handler.sendMessage(message);
				}

			}
		}.start();

	}

	private void checkUpdate() {
		new Thread() {

//			private String loadimageurl;
			private String isforce;

			public void run() {

				Message msg = Message.obtain();
				try {
					URL url = new URL(ApiInterface.UPDATE_URL);
					// 联网
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					// 请求方式
					conn.setRequestMethod("GET");
					// 请求超时时间
					conn.setConnectTimeout(3000);
					// 获取请求返回码
					int code = conn.getResponseCode();
					if (code == 200) {// 联网成功
						InputStream inputStream = conn.getInputStream();
						// 把流转化为string
						String result = StreamTools.readFromStream(inputStream);
						Log.i("联网情况：", "联网成功了" + result);
						// json解析
						JSONObject obj = new JSONObject(result);
						// 从服务器获取到版本信息
						String version = (String) obj.get("version");
						// String version = obj.getString("version");
						Log.i("version", version);
						description = (String) obj.get("description");
						Log.i("version", description);
						apkurl = (String) obj.get("moshudriverapkurl");
						Log.i("version", apkurl);

					/*	loadimageurl = (String) obj.get("loadimageurl");
						Log.i("loadimageurl", loadimageurl);*/

						isforce = (String) obj.get("isforce");

						mEditor.putString("isforce", isforce);
//						mEditor.putString("loadimageurl", loadimageurl);
						mEditor.commit();

						// 判断当前版本和服务器的是否匹配
						if (getVersionName().equals(version)) {
							// 版本一致，不需要进行更新
							redirectto();
						} else {
							// 进行版本更新
							msg.what = SHOW_UPDATE_DIALOG;

						}
					}

				} catch (MalformedURLException e) {
					msg.what = URL_ERROR;
					e.printStackTrace();
				} catch (IOException e) {
					msg.what = NETWORK_ERROR;
					e.printStackTrace();
				} catch (JSONException e) {
					msg.what = JSON_ERROR;
					e.printStackTrace();
				} finally {
					handler.sendMessage(msg);
				}
			}

		}.start();

	}

	private Handler handler = new Handler() {
		// private MyProgressDialog myProgressDialog;

		// 处理消息
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case URL_ERROR:// URL错误
				redirectto();
				Toast.makeText(getApplicationContext(), "URL错误", 0).show();
				break;
			case NETWORK_ERROR:// 网络异常
				redirectto();
				Toast.makeText(SplashActivity.this, "网络异常", 0).show();
				break;
			case JSON_ERROR:// JSON解析出错
				redirectto();
				Toast.makeText(SplashActivity.this, "JSON解析出错", 0).show();
				break;
			// 获取到新版本，显示升级的对话框
			case SHOW_UPDATE_DIALOG:
				showUpdateDialog();
				break;

			case LOADIMAGE:
				System.out.println("加载缓存图片");
				rl_began.setBackground(drawable);
				break;

			// case SHOW_UPDATE_PROGRESS:
			// System.out.println("升级对话框==============");
			// if (!"".equals(progress)) {
			// Looper.prepare();
			// myProgressDialog = new MyProgressDialog(
			// SplashActivity.this, "当前更新进度：" + progress + "%");
			// myProgressDialog.show();
			// Looper.loop();
			// }
			// break;
			//
			// case CANCLE_UPDATE_PROGRESS:
			// myProgressDialog.dismiss();
			// break;
			default:
				break;
			}
		}

	};
	private String loadimageurl;
	private String testurl;

	private void showUpdateDialog() {
		final MyDialog dialog = new MyDialog(SplashActivity.this, description);
		dialog.positive.setText("立刻升级");
		dialog.positive.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!"".equals(progress)) {
					myProgressDialog = new MyProgressDialog(
							SplashActivity.this, "更新进度：" + progress + "%");
					myProgressDialog.show();
				}
				dowmLoadAndInstall();
				dialog.dismiss();
			}
		});
		dialog.negative.setText("下次再说");
		dialog.negative.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String isforce = mShared.getString("isforce", "");
				if (Integer.parseInt(isforce) == 1) {
					dialog.dismiss();
					System.exit(0);
				} else {
					dialog.dismiss();
					redirectto();
				}
			}
		});
		dialog.setCancelable(false);
		dialog.show();

		// AlertDialog.Builder builder = new Builder(SplashActivity.this);
		// builder.setTitle("提示升级");
		// builder.setCancelable(false);
		// builder.setOnCancelListener(new OnCancelListener() {
		//
		// @Override
		// public void onCancel(DialogInterface dialog) {
		// dialog.dismiss();
		// }
		// });
		// // 版本描述
		// builder.setMessage(description);
		// builder.setPositiveButton("立刻升级", new OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		//
		// }
		// });
		// builder.setNegativeButton("下次再说", new OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// redirectto();// 进入主页面
		// }
		//
		// });
		// builder.show();
	}

	protected void dowmLoadAndInstall() {

		// 下载APK，并且替换安装
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sdcard存在
			// afnal
			FinalHttp finalhttp = new FinalHttp();
			finalhttp.download(apkurl, Environment
					.getExternalStorageDirectory().getAbsolutePath()
					+ "/MoShuDriver.apk", new AjaxCallBack<File>() {

				@Override
				public void onFailure(Throwable t, int errorNo, String strMsg) {
					t.printStackTrace();
					Toast.makeText(getApplicationContext(), "下载失败", 1).show();
					myProgressDialog.dismiss();
					redirectto();
					super.onFailure(t, errorNo, strMsg);
				}

				// 通知栏显示下载进度
				@Override
				public void onLoading(long count, long current) {
					// TODO Auto-generated method stub
					super.onLoading(count, current);

					mNotificationManager = (NotificationManager) getApplication()
							.getSystemService(NOTIFICATION_SERVICE);
					// 当前下载百分比

					progress = (int) (current * 100 / count);

					NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
					Notification notif = new Notification();
					notif.icon = R.drawable.logo;
					notif.tickerText = "新通知";
					// 通知栏显示所用到的布局文件
					notif.contentView = new RemoteViews(getPackageName(),
							R.layout.content_view);
					// notif.contentIntent = pIntent;
					manager.notify(0, notif);
					notif.contentView.setTextViewText(
							R.id.tv_download_progress, progress + "%");
					notif.contentView.setProgressBar(
							R.id.content_view_progress, 100, progress, false);
					manager.notify(0, notif);
					// msg.what=SHOW_UPDATE_PROGRESS;
					myProgressDialog.setText("更新进度：" + progress + "%");
					myProgressDialog.setCanceledOnTouchOutside(false);

				}

				@Override
				public void onSuccess(File t) {
					// TODO Auto-generated method stub
					super.onSuccess(t);
					myProgressDialog.dismiss();
					installAPK(t);
				}

				/**
				 * 安装APK
				 * 
				 * @param t
				 */
				private void installAPK(File t) {
					Intent intent = new Intent();
					intent.setAction("android.intent.action.VIEW");
					intent.addCategory("android.intent.category.DEFAULT");
					intent.setDataAndType(Uri.fromFile(t),
							"application/vnd.android.package-archive");
					startActivity(intent);
				}
			});
		} else {
			Toast.makeText(getApplicationContext(), "没有sdcard，请安装上再试", 0)
					.show();
			return;
		}

		// handler.sendMessage(msg);
	}

	private void enterHome() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, SlidingActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
		finish();
	}

	// 得到版本信息
	private String getVersionName() {
		// 用来管理手机的APK
		PackageManager pManager = getPackageManager();
		try {
			// 得到知道APK的功能清单文件
			PackageInfo info = pManager.getPackageInfo(getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	};

	private void redirectto() {
		boolean isFirstRunLead = mShared.getBoolean("isFirstRunLead", true);
		if (isFirstRunLead) {
			Intent intent = new Intent(this, LeadActivity.class);
			startActivity(intent);
			// overridePendingTransition(R.anim.push_right_in,
			// R.anim.push_right_out);
			finish();
		} else {
			if (mShared.getBoolean("isLogin", false)) {
				enterHome();
			} else {
				mEditor.putBoolean("isjpush", false);
				mEditor.putBoolean("isLogin", false);
				mEditor.putString("user", "");
				mEditor.putInt("uid", 0);
				mEditor.putString("sid", "");
				mEditor.commit();
				SESSION.getInstance().uid = mShared.getInt("uid", 0);
				SESSION.getInstance().sid = mShared.getString("sid", "");
				Intent intent = new Intent(this, B0_SigninActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.push_right_in,
						R.anim.push_right_out);
				finish();
			}
		}

	}
}
